<template>
  <!-- 头部 -->
  <view class="w-full bg-gradient-to-b from-[#B0ED90] to-[#3CEBBB] flex 
    justify-start items-end px-[20rpx] pb-[18rpx] box-border relative"
    :style="{ height: headerHeight + 'px', paddingTop: statusBarHeight + 'px' }">
    <view class="absolute bottom-[196rpx] left-[60rpx]">
      <image src="/src/static/images/logo.png" class="w-[272rpx] h-[58rpx]" />
      <view class="text-[40rpx] font-bold color-[#003309] mb-[20rpx]">欢迎加入强脑科技！</view>
    </view>
  </view>
  <!-- 内容 -->
  <view class="w-full flex items-center justify-center relative top-[-130rpx]">
    <view class="w-full h-[800rpx] bg-white rounded-t-[22rpx] px-[60rpx] pt-[80rpx] box-border">
      <!-- 账号输入框 -->
      <view class="form-item">
        <view class="input-wrapper">
          <wd-icon name="user" size="40rpx" color="#777"></wd-icon>
          <input v-model="account" type="text" placeholder="请输入账号" class="input-field"
            placeholder-class="input-placeholder" @input="formErrors.account = ''" />
        </view>
        <view v-if="formErrors.account" class="error-text">
          {{ formErrors.account }}
        </view>
      </view>

      <!-- 密码输入框 -->
      <view class="form-item">
        <view class="input-wrapper mt-[40rpx]">
          <wd-icon name="lock-on" size="40rpx" color="#777"></wd-icon>
          <input 
            v-model="password" 
            :password="!showPassword" 
            placeholder="请输入密码" 
            class="input-field"
            placeholder-class="input-placeholder" 
            @input="formErrors.password = ''" 
          />
          <view class="password-toggle user-select-none cursor-pointer" @click="showPassword = !showPassword">
            <wd-icon 
              :name="showPassword ? 'view' : 'eye-close'" 
              size="40rpx" 
              color="#777"
            ></wd-icon>
          </view>
        </view>
        <view v-if="formErrors.password" class="error-text">
          {{ formErrors.password }}
        </view>
      </view>

      <!-- 登录按钮 -->
      <view class="login-btn mt-[60rpx]" @click="handleLogin">
        <view v-if="isLoading" class="loading-content">
          <text class="loading-text">登录中...</text>
        </view>
        <text v-else>登录</text>
      </view>

      <!-- 底部协议选择框 -->
      <view class="flex justify-center">
        <wd-checkbox v-model="isAgree" shape="dot" checked-color="#8cec9d" class="mt-[60rpx]" @click="toggleAgree">
        <text class="text-[24rpx] color-[#999]">我已认真阅读并同意</text>
        <text class="text-[24rpx] color-[#1a9c34] ml-[8rpx]" @click.stop="handlePrivacyXieyi">《用户协议》</text>
        <text class="text-[24rpx] color-[#999]">和</text>
        <text class="text-[24rpx] color-[#1a9c34] ml-[8rpx]" @click.stop="handlePrivacyZhengce">《隐私政策》</text>
        </wd-checkbox>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed } from 'vue'
import { throttle } from 'wot-design-uni/components/common/util'
import { useTokenStore } from '@/store/token'
import { useUserStore } from '@/store/user'
import { tabbarList } from '@/tabbar/config'
import { isPageTabbar } from '@/tabbar/store'
import { ensureDecodeURIComponent } from '@/utils'
import { parseUrlToObj } from '@/utils/index'

definePage({
  style: {
    navigationStyle: 'custom',
    navigationBarTitleText: '登录',
  },
})

// 获取系统信息
const systemInfo = uni.getSystemInfoSync()
const statusBarHeight = ref(systemInfo.statusBarHeight || 0)

// 基础高度（原来的 440rpx 转换为 px）+ 状态栏高度
const baseHeight = computed(() => {
  // 440rpx 按照设计稿 750rpx 宽度计算
  const rpxToPx = systemInfo.windowWidth / 750
  return 440 * rpxToPx
})

const headerHeight = computed(() => {
  return baseHeight.value + statusBarHeight.value
})

// 表单数据
const account = ref('')
const password = ref('')

// 密码可见性状态
const showPassword = ref(false)

// 表单验证状态
const formErrors = ref({
  account: '',
  password: '',
})

// 协议同意状态
const isAgree = ref(false)

// 登录状态
const isLoading = ref(false)

// 重定向URL
const redirectUrl = ref('')

// 状态管理
const userStore = useUserStore()
const tokenStore = useTokenStore()

// 页面加载时获取重定向URL
onLoad((options) => {
  console.log('login options: ', options)
  if (options.redirect) {
    redirectUrl.value = ensureDecodeURIComponent(options.redirect)
  }
  else {
    redirectUrl.value = tabbarList[0].pagePath
  }
  console.log('redirectUrl.value: ', redirectUrl.value)
})

// 表单验证
function validateForm() {
  formErrors.value = {
    account: '',
    password: '',
  }

  let isValid = true

  if (!account.value.trim()) {
    formErrors.value.account = '请输入账号'
    isValid = false
  }

  if (!password.value.trim()) {
    formErrors.value.password = '请输入密码'
    isValid = false
  } else if (password.value.length < 6) {
    formErrors.value.password = '密码长度不能少于6位'
    isValid = false
  }



  return isValid
}

// 登录方法
const handleLogin = throttle(async () => {
  // ⭐ 检查是否同意协议
  if (!isAgree.value) {
    uni.showToast({
      title: '请先阅读并同意《用户协议》和《隐私政策》内容',
      icon: 'none',
    })
    return false
  }

  // 如果已经登录，则直接跳转上一页
  if (tokenStore.hasLogin) {
    uni.navigateBack()
    return
  }

  // 表单验证
  if (!validateForm()) {
    return
  }

  isLoading.value = true

  try {
    // 调用登录接口
    await tokenStore.login({
      type: 'username',
      username: account.value.trim(),
      password: password.value.trim(),
    })

    console.log('登录成功，准备跳转:', redirectUrl.value)

    // 登录成功后跳转
    handleLoginSuccess()
  }
  catch (error) {
    // 错误提示已在 http.ts 中统一处理，这里只打印日志
    console.log('登录失败', error)
  }
  finally {
    isLoading.value = false
  }
}, 1000)

// 处理登录成功后的跳转逻辑
function handleLoginSuccess() {
  let path = redirectUrl.value
  if (!path.startsWith('/')) {
    path = `/${path}`
  }
  const { path: _path, query } = parseUrlToObj(path)
  console.log('_path:', _path, 'query:', query, 'path:', path)
  console.log('isPageTabbar(_path):', isPageTabbar(_path))

  if (isPageTabbar(_path)) {
    // 经过我的测试 switchTab 不能带 query 参数, 不管是放到 url  还是放到 query ,
    // 最后跳转过去的时候都会丢失 query 信息
    uni.switchTab({
      url: path,
    })
  }
  else {
    // 自己决定是 redirectTo 还是 navigateBack
    // uni.redirectTo({
    //   url: path,
    // })
    uni.navigateBack()
  }
}

// 用户协议
const handlePrivacyXieyi = () => {
  const agreementContent = `
    <h3>用户协议</h3>
    <p>欢迎阅读本用户协议。在使用本应用之前，请仔细阅读并理解本协议的所有内容。</p>
    <p>一、服务条款</p>
    <p>用户在使用本应用时，应当遵守相关法律法规，不得进行任何违法违规行为。</p>
    <p>二、用户责任</p>
    <p>用户对其账户下的所有行为及后果承担责任。</p>
    <p>三、服务免责</p>
    <p>本应用尽力为用户提供最佳服务，但不对因不可抗力等因素造成的损失承担责任。</p>
  `
  const title = '用户协议'
  uni.navigateTo({
    url: `/pages-children/richText/index?title=${title}&content=${encodeURIComponent(agreementContent)}`
  })
}

// 隐私政策
const handlePrivacyZhengce = () => {
  const privacyContent = `
    <h3>隐私政策</h3>
    <p>本隐私政策说明了我们如何收集、使用、保护和披露用户信息。</p>
    <p>一、信息收集</p>
    <p>我们可能收集用户的账户信息、使用数据等信息。</p>
    <p>二、信息使用</p>
    <p>收集的信息将仅用于改进服务和用户体验。</p>
    <p>三、信息保护</p>
    <p>我们采取措施保护用户信息的安全，防止未授权访问。</p>
    <p>四、信息共享</p>
    <p>除法律要求外，我们不会与第三方共享用户信息。</p>
  `
  const title = '隐私政策'
  uni.navigateTo({
    url: `/pages-children/richText/index?title=${title}&content=${encodeURIComponent(privacyContent)}`
  })
}

// ⭐ 切换协议同意状态
const toggleAgree = () => {
  isAgree.value = !isAgree.value
}
</script>

<style>
page {
  background-color: #FFF;
}
</style>

<style lang="scss" scoped>
.form-item {
  margin-bottom: 20rpx;
}

.input-wrapper {
  display: flex;
  align-items: center;
  background: #F5F5F5;
  border-radius: 50rpx;
  padding: 0 40rpx;
  height: 96rpx;
  transition: all 0.3s ease;
}

.input-field {
  flex: 1;
  margin-left: 20rpx;
  font-size: 32rpx;
  color: #282828;
}

.password-toggle {
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  margin-left: 12rpx;
}

.input-placeholder {
  color: #999;
  font-size: 32rpx;
}

.error-text {
  color: #FF0000;
  font-size: 24rpx;
  margin-top: 12rpx;
  padding-left: 40rpx;
}

.login-btn {
  width: 100%;
  height: 96rpx;
  background: linear-gradient(135deg, #B0ED90, #3CEBBB);
  border-radius: 50rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 36rpx;
  font-weight: bold;
  color: #003309;
  box-shadow: 0 4rpx 12rpx rgba(60, 235, 187, 0.3);
  transition: all 0.3s ease;

  &:active {
    transform: translateY(2rpx);
    opacity: 0.9;
  }

  .loading-content {
    display: flex;
    align-items: center;
    justify-content: center;

    .loading-text {
      margin-left: 12rpx;
    }
  }
}
</style>
